package com.chezhujie.www.controller.api;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import com.chezhujie.www.domain.Identitycard;
import com.chezhujie.www.enums.Approvestatus;
import com.chezhujie.www.service.IdentitycardService;
import com.xy.core.page.Pagination;
import com.xy.core.utils.ConvertObj;
import com.xy.core.utils.Fileupload;
import com.xy.core.utils.UUIDUtils;
import com.xy.user.base.controller.BaseController;

/**
 * 认证信息 Created by 汤伟杰 on 2017/5/23.
 */
@Controller
@RequestMapping("/api/identitycard")
public class IdentitycardController extends BaseController<Identitycard> {
	@Autowired
	private IdentitycardService identitycardService;

	/** 列表 **/
	@RequestMapping("/list.do")
	public String list(Integer pageNo, Integer pageSize,
			Identitycard identitycard, HttpServletRequest req,
			HttpServletResponse resp, ModelMap model) {
		setMsg(identitycard, req, model);
		if (pageNo == null) {
			pageNo = 1;
		}
		if (pageSize == null) {
			pageSize = 0;
		}
		try {
			Map<String, Object> params = ConvertObj.toMap(identitycard);
			Pagination pagination = identitycardService.list(pageNo.intValue(),
					pageSize.intValue(), params, model);
			model.addAttribute("pagination", pagination);
		} catch (Exception e) {
			e.printStackTrace();
			model.addAttribute("failed", "获取认证信息列表失败!" + e.getMessage());
		}
		model.addAttribute("entity", identitycard);
		return "identitycard/list";
	}

	/**
	 * api接口认证信息列表
	 * 
	 * @param pageNo
	 * @param pageSize
	 * @param identitycard
	 * @param req
	 * @param resp
	 * @param model
	 * @throws Exception
	 */
	@RequestMapping("/apiList.jn")
	public void apiList(Integer pageNo, Integer pageSize,
			Identitycard identitycard, HttpServletRequest req,
			HttpServletResponse resp, ModelMap model) throws Exception {
		if (pageNo == null) {
			pageNo = 1;
		}
		if (pageSize == null) {
			pageSize = 0;
		}
		try {
			Map<String, Object> params = ConvertObj.toMap(identitycard);
			Pagination pagination = identitycardService.apilist(
					pageNo.intValue(), pageSize.intValue(), params, model);
			jsonResult(1, "", "", pagination, resp);
		} catch (Exception e) {
			e.printStackTrace();
			jsonResult(0, "", "获取认证信息列表失败!" + e, "", resp);
		}

	}

	/**
	 * api接口认证信息详情
	 * 
	 * @param req
	 * @param resp
	 * @param model
	 * @throws Exception
	 */
	@RequestMapping("/apiDetail.jn")
	public void apiDetail(HttpServletRequest req, HttpServletResponse resp,
			ModelMap model) throws Exception {
		Map<String, Object> params = new HashMap<String, Object>();
		Enumeration<String> enumeration = req.getParameterNames();
		if (enumeration.hasMoreElements()) {
			String next = enumeration.nextElement();
			params.put(next, req.getParameter(next));
		}

		try {
			Map<String, Object> result = identitycardService
					.getApiDetail(params);
			jsonResult(1, "", "", result, resp);
		} catch (Exception e) {
			e.printStackTrace();
			jsonResult(0, "99", "获取认证信息详情失败!" + e, "", resp);
		}

	}

	/** api测试页面 **/
	@RequestMapping("/apiTest.do")
	public String apiList(HttpServletRequest req, HttpServletResponse resp,
			ModelMap model) throws Exception {
		model.addAttribute("entity", new HashMap<String, Object>());
		return "identitycard/apiTest";

	}

	/** 保存 **/
	@RequestMapping("/save.do")
	public String save(
			Identitycard identitycard,
			@RequestParam(value = "fileIdCardFace", required = false) MultipartFile multipartFile_IdCardFace,
			@RequestParam(value = "fileIdCardReverse", required = false) MultipartFile multipartFile_IdCardReverse,
			HttpServletRequest req, HttpServletResponse resp, ModelMap model) {
		try {

			if (StringUtils.isNotBlank(identitycard.getIdentitycardId())) {
				String idCardFace = identitycard.getIdCardFace();
				setIdCardFace(identitycard, multipartFile_IdCardFace, req);
				String idCardReverse = identitycard.getIdCardReverse();
				setIdCardReverse(identitycard, multipartFile_IdCardReverse, req);
				identitycardService.update(identitycard);
				Fileupload.deleteFile(req, idCardFace);
				Fileupload.deleteFile(req, idCardReverse);

			} else {
				identitycard.setIdentitycardId(UUIDUtils.getUUID());
				setIdCardFace(identitycard, multipartFile_IdCardFace, req);
				setIdCardReverse(identitycard, multipartFile_IdCardReverse, req);
				identitycardService.insert(identitycard);
			}
			model.addAttribute("success", "保存认证信息成功");
		} catch (Exception e) {
			e.printStackTrace();
			model.addAttribute("failed", "保存认证信息失败!详情：" + e.getMessage());
		}
		return "redirect:list.do";
	}

	private void setIdCardFace(Identitycard identitycard,
			MultipartFile multipartFile, HttpServletRequest req)
			throws Exception {
		if ((!multipartFile.isEmpty()) && multipartFile.getSize() > 0) {
			String basePath = req.getSession().getServletContext()
					.getRealPath("/");
			String path = basePath
					+ "upload/identitycard/"
					+ identitycard.getIdentitycardId()
					+ "-"
					+ System.currentTimeMillis()
					+ multipartFile.getOriginalFilename().substring(
							multipartFile.getOriginalFilename()
									.lastIndexOf("."));
			Fileupload.createDir(basePath + "upload/identitycard/");

			InputStream in = multipartFile.getInputStream();
			FileOutputStream out = new FileOutputStream(path);
			try {
				IOUtils.copy(in, out);
			} catch (IOException e) {
				e.printStackTrace();
				throw new Exception("上传图片失败！");
			} finally {
				IOUtils.closeQuietly(in);
				IOUtils.closeQuietly(out);
			}

			String idCardFace = "/" + path.replace(basePath, "");
			identitycard.setIdCardFace(idCardFace);
		}
	}

	private void setIdCardReverse(Identitycard identitycard,
			MultipartFile multipartFile, HttpServletRequest req)
			throws Exception {
		if ((!multipartFile.isEmpty()) && multipartFile.getSize() > 0) {
			String basePath = req.getSession().getServletContext()
					.getRealPath("/");
			String path = basePath
					+ "upload/identitycard/"
					+ identitycard.getIdentitycardId()
					+ "-"
					+ System.currentTimeMillis()
					+ multipartFile.getOriginalFilename().substring(
							multipartFile.getOriginalFilename()
									.lastIndexOf("."));
			Fileupload.createDir(basePath + "upload/identitycard/");

			InputStream in = multipartFile.getInputStream();
			FileOutputStream out = new FileOutputStream(path);
			try {
				IOUtils.copy(in, out);
			} catch (IOException e) {
				e.printStackTrace();
				throw new Exception("上传图片失败！");
			} finally {
				IOUtils.closeQuietly(in);
				IOUtils.closeQuietly(out);
			}

			String idCardReverse = "/" + path.replace(basePath, "");
			identitycard.setIdCardReverse(idCardReverse);
		}
	}

	/** 详情 **/
	@RequestMapping("/detail.do")
	public String detail(@RequestParam(required = true) String identitycardId,
			Identitycard identitycard, HttpServletRequest req,
			HttpServletResponse resp, ModelMap model) {
		setMsg(identitycard, req, model);
		try {
			Identitycard entity = identitycardService.queryById(identitycard
					.getIdentitycardId());
			model.addAttribute("entity", entity);
		} catch (Exception e) {
			e.printStackTrace();
			model.addAttribute("failed", "查询认证信息出错!详情：" + e.getMessage());
		}
		return "identitycard/detail";
	}

	/** 新增或修改 **/
	@RequestMapping("/add.do")
	public String add(Identitycard identitycard, HttpServletRequest req,
			HttpServletResponse resp, ModelMap model) {
		setMsg(identitycard, req, model);
		if (StringUtils.isNotBlank(identitycard.getIdentitycardId())) {
			identitycard = identitycardService.queryById(identitycard
					.getIdentitycardId());
			model.addAttribute("entity", identitycard);
		}
		return "identitycard/add";
	}

	/** 删除 **/
	@RequestMapping("/delete.do")
	public String delete(@RequestParam(required = true) String identitycardId,
			Identitycard identitycard, HttpServletRequest req,
			HttpServletResponse resp, ModelMap model) {
		try {
			identitycardService.deleteById(identitycard.getIdentitycardId());
		} catch (Exception e) {
			e.printStackTrace();
			model.addAttribute("failed", e.getMessage());
		}
		return "redirect:list.do";
	}

	private void setMsg(Identitycard identitycard, HttpServletRequest req,
			ModelMap model) {
		model.addAttribute("failed", req.getParameter("failed"));
		model.addAttribute("success", req.getParameter("success"));
		model.addAttribute("entity", identitycard);
	}

	/**
	 * 
	 * 方法名：listByUserId 根据用户id查询认证信息 创建人：RUI 时间：2017年8月18日-下午1:29:58
	 * 
	 * @param userInifoId
	 * @param req
	 * @param resp
	 * @param model
	 * @throws Exception
	 *             void
	 * @exception
	 * @since 1.0.0
	 */
	@RequestMapping("/listByUserId.do")
	public void listByUserId(String userInifoId, HttpServletRequest req,
			HttpServletResponse resp, ModelMap model) throws Exception {

		if (StringUtils.isBlank(userInifoId)) {

			jsonResult(0, "178", "用户为空", "", resp);
			return;
		}
		try {
			Map<String, Object> params = new HashMap<String,Object>();
			params.put("userInfoId", userInifoId);
			Identitycard identitycard = identitycardService.queryByOne(params);
			jsonResult(1, "", "", identitycard, resp);
		} catch (Exception e) {
			e.printStackTrace();
			jsonResult(0, "179", "根据用户id查询认证信息失败!", "", resp);
		}

	}

	/**
	 * 
	 * 方法名：updateOrInsertIdentitycard 新增 或修改认证信息 创建人：RUI 时间：2017年8月18日-下午1:44:52
	 * 
	 * @param identitycard
	 * @param req
	 * @param resp
	 * @param model
	 * @throws Exception
	 *             void
	 * @exception
	 * @since 1.0.0
	 */
	@RequestMapping("/updateOrInsertIdentitycard.do")
	public void updateOrInsertIdentitycard(Identitycard identitycard,
			HttpServletRequest req, HttpServletResponse resp,
			ModelMap model/*,@RequestParam(value = "file", required = false) MultipartFile [] multipartFiles*/)
			throws Exception {

		try {
			
			if (StringUtils.isBlank(identitycard.getUserInfoId())) {

				jsonResult(0, "178", "用户为空", "", resp);
				return;
			}
			
			String pathRoot = req.getSession().getServletContext().getRealPath("");
			File fileDir = new File(pathRoot + "/upload");
			if (!fileDir.exists()) {
				fileDir.mkdir();
			}
		
			if(StringUtils.isNotBlank(identitycard.getIdCardFace())){
				String picName = UUIDUtils.getDateUUID();
				String path = "/upload/" + picName+"-"+System.currentTimeMillis() + ".jpg";// 数据库保存路径
				boolean isTrue =  com.xy.core.utils.ImgBase64Util.generateImage(identitycard.getIdCardFace(), pathRoot
						+ path);
				if (isTrue == false) {
					jsonResult(0, "120", "转存头像失败", "", resp);
					return;
				}
				identitycard.setIdCardFace(path);
			}
			
			if(StringUtils.isNotBlank(identitycard.getIdCardReverse())){
				String picName = UUIDUtils.getDateUUID();
				String path = "/upload/" + picName+"-"+System.currentTimeMillis() + ".jpg";// 数据库保存路径
				boolean isTrue =  com.xy.core.utils.ImgBase64Util.generateImage(identitycard.getIdCardReverse(), pathRoot
						+ path);
				if (isTrue == false) {
					jsonResult(0, "120", "转存头像失败", "", resp);
					return;
				}
				identitycard.setIdCardReverse(path);
				
			}

			Map<String, Object> params = new HashMap<String,Object>();
			params.put("userInfoId", identitycard.getUserInfoId());
			Identitycard ident = identitycardService.queryByOne(params);

			if (StringUtils.isBlank(identitycard.getIdentitycardId())) {

				if (null != ident) {
					jsonResult(0, "180", "认证信息重复", "", resp);
					return ;
				}
				identitycard.setIdentitycardId(UUIDUtils.getUUID());
				identitycardService.insert(identitycard);
				jsonResult(1, "", "", "", resp);
			} else {

				Integer status = ident.getStatus();
				if (status != identitycard.getStatus()) {
					jsonResult(0, "181", "非法请求", "", resp);
				}
				if (status == Approvestatus.SUCCESS.getIndex()) {
					jsonResult(0, "182", "只用审批不通过才可以修改信息", "", resp);
					return;
				}
				identitycard.setStatus(Approvestatus.RUNNING.getIndex());  //修改设置审批状态为审核中
				identitycardService.update(identitycard);
				jsonResult(1, "", "", "", resp);
			}

		} catch (Exception e) {
			e.printStackTrace();
			jsonResult(0, "183", "新增 或修改认证信息失败!", "", resp);
		}

	}

}
